from collections import defaultdict

# 1.

# d = defaultdict(lambda :0)
# with open('E:/pythonstudy/magedu/project/temp/sample.txt',encoding='UTF-8') as f:
#     for line in f:
#         res = []
#         chars = set(r"""/\,"'.()-`""")
#         for k in line:
#             if k  in chars:
#                 res.append(' ')
#             else:
#                 res.append(k)
#         key = ''.join(res).split()
#         for k in key:
#             d[k] +=1
# print(sorted(d.items(),key=lambda x:x[1],reverse=True)[:10])


# 2. 包装成函数
file = 'E:/pythonstudy/magedu/project/temp/sample.txt'

def _make_key(line,chars=set(r"""/\,"' .([])-`""")):
    return ''.join((' ' if k in chars else k for k in line )).split()
    # 这里的三元表达式if加for逻辑比较长，对他人的阅读理解会有干扰，可以换行

def words_count(file,encoding='UTF-8'):
    d = defaultdict(lambda :0)
    with open(file,encoding=encoding) as f:
        for line in f:
            for k in _make_key(line):
                d[k.lower()] +=1
    return d

print(sorted(words_count(file).items(),key=lambda x:x[1],reverse=True)[:10])

# 总体做得不错
